#include <string>
#include "SmtpClient.h"
#include "TcpClient.h"
#include "SmtpProtocol.h"


using namespace std;


SmtpClient::SmtpClient( std::string ip, int port)
{
	_init = false;

	_tcpClient = new TcpClient( ip, port );

	if( true == _tcpClient->isInit() )
		_init = true;
}

SmtpClient::~SmtpClient()
{
	delete _tcpClient;
}

bool SmtpClient::isInit() const
{
	return _init;
}

int SmtpClient::sendMail ( const Mail & mail)
{
	string	formatedMail;
	int	ret;
	int	bytesReceived = 1;
	int	bufferTmpSize = 1024;
	char *	bufferTmp = new char[bufferTmpSize];

	formatedMail = SmtpProtocol::formatMail(mail);

	if( -1 == _tcpClient->receiveData( bufferTmp, bufferTmpSize ) )
		cerr << "Warning: Reception problem detected!" << endl;
	cout << "Datas received: " << bufferTmp << endl;

	ret = _tcpClient->sendData( (char *)formatedMail.c_str(), strlen(formatedMail.c_str()) );

	while( bytesReceived > 0 )
	{
		bytesReceived = _tcpClient->receiveData( bufferTmp, bufferTmpSize );
		if( -1 == bytesReceived )
			cerr << "Warning: Reception problem detected!" << endl;
		else cout << "Datas received: " << bufferTmp << endl;
	}

	delete bufferTmp;

	return ret;
}
